package org.azj.ImageEditor;

import java.io.File;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.sql.DataSource;

import org.azj.dbOperatorComponent.IDbNonQueryOperation;
import org.azj.dbOperatorComponent.OperableTable;

import com.ibm.db2.jcc.DB2SimpleDataSource;

public class main {

	public static void main(String[] args) {
		ImageEditor ieAdd = new ImageEditor();
		List<String> imgList = new ArrayList<String>();
		File directory = new File("");
		for (int i = 0 ; i < 4; i++) {
			String fullPathString = 
					String.format("%s%s%d%s", 
							directory.getAbsolutePath(), "\\testdata\\", i + 1 , ".jpg");
			imgList.add(fullPathString);
		}
		
		
		// 模拟添加病人记录的情形
		ImagePreparer ipAdd = new AddPatientPreparer();
		ieAdd.setImagePreparer(ipAdd);
		String tmpFolderPath = 
				System.getProperty("user.dir") + "\\tmp\\test_only";
		File tmpFile = new File(tmpFolderPath);
		tmpFile.deleteOnExit();
		tmpFile.mkdirs();
		ieAdd.setImageFolderPath(tmpFolderPath);
		if (!ieAdd.showPictures(imgList) ) {
			System.out.println("无法show image");
		}
		List<String> missingPicList = ieAdd.getMissingPictures();
		for (String imgPathString : missingPicList) {
			System.out.println(imgPathString);	
		}
		
		// 清空中间文件夹
		SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
		tmpFolderPath = 
				System.getProperty("user.dir") + "\\tmp\\" + sDateFormat.format(new Date());
		File file = new File(tmpFolderPath);
		file.deleteOnExit();
		file.mkdirs();
		
		String lastElem = imgList.get(imgList.size() - 1);
		imgList.clear();
		imgList.add(lastElem);
		
		// 模拟修改病人记录的情形
		DB2SimpleDataSource db2ds = new DB2SimpleDataSource();
		db2ds.setDatabaseName("DBTEST");                          
        // Description for documentation
		db2ds.setUser("aicro");
        // Assign the user ID
		db2ds.setPassword("aizhijie1104");
        
		DataSource dataSource = db2ds;
		try {
			ipAdd = new RectifyPatientPrepare(
					dataSource, "AICRO", "TBL_IMAGE", "IMAGE", "ID = \'%s\'");
		} catch (Exception e) {
			System.out.println("连接出错," + e.getMessage());
		}
		ieAdd.setImageFolderPath(tmpFolderPath);
		ieAdd.setImagePreparer(ipAdd);
		String fullPathString = "1";
		imgList.add(fullPathString);
		if (!ieAdd.showPictures(imgList) ) {
			System.out.println("无法show image");
		}
		missingPicList = ieAdd.getMissingPictures();
		for (String imgPathString : missingPicList) {
			System.out.println(imgPathString);	
		}
		
		ieAdd.dispose();
		
		// 以真是环境进行测试
		showPicAndDelete();
	}
	
	// 以后这个方法就直接拿去用
	private static void showPicAndDelete() {
		// 准备测试数据
		DB2SimpleDataSource dataSource = new DB2SimpleDataSource();
		dataSource.setDatabaseName("DBTEST");                          
        // Description for documentation
		dataSource.setUser("aicro");
        // Assign the user ID
		dataSource.setPassword("aizhijie1104");
		
		File directory = new File("");
		String denotation = "";
		
		for (int i = 0 ; i < 4; i++) {
			denotation += 
					String.format("%s%s%d%s", 
							directory.getAbsolutePath(), "\\testdata\\", i + 1 , ".jpg") + ";";
		}
		denotation += "1;3;";
		
		// 临时文件夹
		SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
		String tmpFolderPath = 
				System.getProperty("user.dir") + "\\tmp\\" + sDateFormat.format(new Date());
		File file = new File(tmpFolderPath);
		file.deleteOnExit();
		file.mkdirs();
		
		// 实际调用的函数
		List<String> missingImgs = null;
		try {
			missingImgs = showImagesAndGetMissingImgs(denotation, tmpFolderPath, dataSource);	
		} catch (Exception e) {
			// TODO: 出现了错误，展示给用户看，
		}
		
		if (false == deleteImages(missingImgs, dataSource)) {
			// TODO: 出现了错误，展示给用户看，
		}
	}
	
	// 参数是我们的image list，以分号分割(也以分号结束）。如果是全路径则是本地文件，如果不是则是数据库中的id
	// 这里只需要修改表的名称等信息和函数签名
	private static List<String> showImagesAndGetMissingImgs(
			String imageDenotation, 
			String tmpFolderPath, 
			DataSource db2ds) {
		// split the denotations with ";"
		String [] imageDenotations = imageDenotation.split(";");
		List<String> imgList = Arrays.asList(imageDenotations);
		
		ImageEditor ieAdd = new ImageEditor();
		ImagePreparer ipAdd = null;
		
		try {
			// TODO 修改表名
			ipAdd = new RectifyPatientPrepare(
					db2ds, "AICRO", "TBL_IMAGE", "IMAGE", "ID = \'%s\'");
			
			ieAdd.setImageFolderPath(tmpFolderPath);
			ieAdd.setImagePreparer(ipAdd);
			
			if (!ieAdd.showPictures(imgList) ) {
				throw new Exception("图片不能被加载!");
			}
			
			return ieAdd.getMissingPictures();
		} 
		catch (Exception e) {
			// TODO 写日志
		}
		finally {
			ieAdd.dispose();
		}
		
		return new ArrayList<String>();
	}
	
	// 调整表名和日志
	private static boolean deleteImages(
			List<String> toDeleteImages, 
			DataSource ds) {
		
		IDbNonQueryOperation tableUnit = null;
		try {
			// TODO 修改表名
			tableUnit = new OperableTable(ds, "AICRO", "TBL_IMAGE");	
		} catch (SQLException e) {
			// TODO 写日志
			return false;
		}
		
		String whereFilter;
		int id = 0;
		
		for (String toDeleteImage : toDeleteImages) {
			try {  
				id = Integer.parseInt(toDeleteImage);
			}  
			catch(NumberFormatException nfe) {  
				continue;  
			}  
			whereFilter = String.format("id = %d", id);
			
			try {
				tableUnit.getDeleteCommand(whereFilter).doCommand(ds);		
			} catch (SQLException e) {
				// TODO 写日志
				return false;
			}
		}
		
		return true;
	}
}
